﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using DiBang.Common;
using DiBang.Sql;
using AForge;
using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;
using Size = System.Drawing.Size;
using System.Runtime.InteropServices;
using System.Windows.Media.Imaging;
using System.Windows;
using System.IO;
using System.Drawing.Imaging;
using System.Configuration;
using System.Data.SqlClient;
using System.IO.Ports;
using System.Threading;


namespace ChangWuDiBang
{
    public partial class FrmDiBangSecInput : Office2007Form
    {
        private FilterInfoCollection videoDevices;
        //private VideoCaptureDevice videoSource;
        private delegate void UpdateTextEventHandler(string text);  //委托，此为重点
        private UpdateTextEventHandler updateText;
        private void UpdateTextBox(string text)
        {
            txtMaoZhong.Text = text;
        }

        private bool closeFlag = false;

        public SerialPort _SerialPort
        {
            get;
            set;
        }

        public UserInfo _UserInfo
        {
            get;
            set;
        }

        public DiBangInfo _DiBangInfo
        {
            get;
            set;   
        }

        private enum InputMode
        {
            MaoZhong,PiZhong,None
        }

        private Enum WeightMode=InputMode.None;

        SqlLib sqlLib = new SqlLib();
        SqlExtend sqlExtend = new SqlExtend();

        public FrmDiBangSecInput()
        {
            this.EnableGlass = false;
            InitializeComponent();
        }

        private void FrmDiBangSecInput_Load(object sender, EventArgs e)
        {
            try
            {
                splitContainer1.Panel1Collapsed = false;
                splitContainer1.Panel2Collapsed = true;

                this.txtUserID.Text = _UserInfo.UserID;
                //一直刷新时间
                InfoSet();
                this.timer1.Enabled = true;
                this.timer1.Start();

                //
                this._SerialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.port_DataReceived);
                updateText = new UpdateTextEventHandler(UpdateTextBox);//实例化委托对象

                //
                lblVDiBang_ID.Text = _DiBangInfo.Dibang_ID;
                txtPiZhong.Text = _DiBangInfo.PiZhong;
                //txtMaoZhong.Text = _DiBangInfo.MaoZhong;
                txtPinMing.Text = _DiBangInfo.PinMing;
                txtCheHao.Text = _DiBangInfo.CheHao;
                txtOther.Text = _DiBangInfo.ChengZhongOther;

                // 枚举所有视频输入设备
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

                foreach (FilterInfo device in videoDevices)
                {
                    cmbFirstCamera.Items.Add(device.Name);
                }
                cmbFirstCamera.SelectedIndex = -1;
            }
            catch (Exception err)
            {
                MessageBoxEx.Show(err.Message, "Warming", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }

        private void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            if (!closeFlag)
            {
                Thread.Sleep(10);
                byte[] readBuffer = new byte[_SerialPort.BytesToRead];
                _SerialPort.Read(readBuffer, 0, readBuffer.Length);

                double dResult = SerialPortProcess.GetBuffer(readBuffer);

                //
                if (dResult > -1)
                {
                    this.Invoke(updateText, new string[] { dResult.ToString() });
                }
            }
        }

        private enum CameraMode
        { 
            CONNECT,DISCONNECT
        }

        private bool FirstCamera(CameraMode mode)
        {
            bool retBool = true;
            if (mode.Equals(CameraMode.CONNECT))
            {
                VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[cmbFirstCamera.SelectedIndex].MonikerString);
                videoSource.DesiredFrameSize = new System.Drawing.Size(320, 240);
                videoSource.DesiredFrameRate = 1;

                vspFirst.VideoSource = videoSource;
                vspFirst.Start();
            }
            else if (mode.Equals(CameraMode.DISCONNECT))
            {
                vspFirst.SignalToStop();
                vspFirst.WaitForStop();
            }
            else
            {
                MessageBoxEx.Show("输入模式不正确!", "Warming", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                retBool = false;    
            }

            return retBool;
        }

        private void btnFirstPhoto_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnFirstPhoto.Text == "拍照")
                {
                    if (vspFirst.IsRunning)
                    {
                        BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                                        vspFirst.GetCurrentVideoFrame().GetHbitmap(),
                                        IntPtr.Zero,
                                         Int32Rect.Empty,
                                        BitmapSizeOptions.FromEmptyOptions());
                        PngBitmapEncoder pE = new PngBitmapEncoder();
                        pE.Frames.Add(BitmapFrame.Create(bitmapSource));

                        MemoryStream ms = new MemoryStream();
                        pE.Save(ms);

                        //Stream转换成图片
                        Image image = Image.FromStream(ms, true);
                        picFirst.Image = image;

                        //Byte[] imgbyte = new Byte[ms.Length];
                        //ms.Read(imgbyte, 0, imgbyte.Length);
                    }
                    
                    //转换视角
                    splitContainer1.Panel1Collapsed = true ;
                    splitContainer1.Panel2Collapsed = false;
                    btnFirstPhoto.Text = "返回";
                }
                else
                {
                    //转换视角
                    splitContainer1.Panel1Collapsed = false;
                    splitContainer1.Panel2Collapsed = true;
                    btnFirstPhoto.Text = "拍照";
                }
            }
            catch (Exception err)
            {
                MessageBoxEx.Show(err.Message, "Warming", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }


        private void btnFirstConnet_Click(object sender, EventArgs e)
        {
            if (btnFirstConnet.Text == "断开")
            {
                if (FirstCamera(CameraMode.DISCONNECT))
                {
                    btnFirstConnet.Text = "连接";
                }
            }
            else
            {
                if (FirstCamera(CameraMode.CONNECT))
                {
                    btnFirstConnet.Text = "断开";
                }
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!sqlExtend.UserPwdCheck(txtUserID.Text.Trim(), txtPwd.Text.Trim()))
                    throw new Exception("用户ID或密码不存在!");

                DialogResult diaR = MessageBoxEx.Show("是否要保存?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (diaR == DialogResult.No)
                    return;

                if (!DiBangCheck())
                {
                    throw new Exception("数据已经被编辑,请确认!");
                }


                string timeKey = sqlExtend.GetTimeKey();
                string imageID = "IMAGE_" + timeKey;

                byte[] byteFirstPic = null;
                if (picFirst.Image != null)
                {
                    MemoryStream msFirst = new MemoryStream();
                    picFirst.Image.Save(msFirst, ImageFormat.Bmp);
                    byteFirstPic = msFirst.GetBuffer();
                    msFirst.Dispose();

                    //存入图片
                    Dictionary<string, object> imageSet = new Dictionary<string, object>();
                    imageSet.Clear();
                    imageSet.Add("IMAGE_ID", imageID);
                    imageSet.Add("FIRST_PHOTO", byteFirstPic);
                    imageSet.Add("CREATE_USER_ID", txtUserID.Text.Trim());
                    imageSet.Add("CREATE_TIME", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
                    imageSet.Add("LAST_EVENT_NAME", "IMAGE_CREATE");
                    imageSet.Add("LAST_EVENT_USER_ID", txtUserID.Text.Trim());
                    imageSet.Add("LAST_EVENT_TIMEKEY", timeKey);
                    sqlLib.InsertTable("DB_IMAGE", imageSet);
                }

                //存入记录的数据
                Dictionary<string, object> dibangSet = new Dictionary<string, object>();
                dibangSet.Clear();
                dibangSet.Add("CHENG_DATE", lblVDate.Text.Trim());
                //dibangSet.Add("PIN_MING", txtPinMing.Text.Trim());
                //dibangSet.Add("CHE_HAO", txtCheHao.Text.Trim());
                dibangSet.Add("OTHER", txtOther.Text.Trim());

                dibangSet.Add("MaoZhong", Base64Encoding.BaseEncoding(txtMaoZhong.Text.Trim()));
                dibangSet.Add("RongQiNum", txtRongQiNum.Text.Trim());
                dibangSet.Add("RongQiZhong", Base64Encoding.BaseEncoding(txtRongQiZhong.Text.Trim()));
                dibangSet.Add("JingZhong", Base64Encoding.BaseEncoding(txtJingZhong.Text.Trim()));
                dibangSet.Add("IMAGE_ID", imageID);

                dibangSet.Add("CompleteFlag", "Y");

                dibangSet.Add("LAST_EVENT_NAME", "称毛重");
                dibangSet.Add("LAST_EVENT_USER_ID", txtUserID.Text.Trim());
                dibangSet.Add("LAST_EVENT_TIMEKEY", timeKey);

                Dictionary<string, object> dibangWhere = new Dictionary<string, object>();
                dibangWhere.Clear();
                dibangWhere.Add("DIBANG_ID", lblVDiBang_ID.Text);

                if (sqlLib.UpdateTable("DB_DIBANG", dibangSet, dibangWhere) >= -1)
                {
                    sqlExtend.MakeDiBangHistory(timeKey);//插入履历
                    MessageBoxEx.Show("输入存入成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //Show出报表界面
                    DiBangPrintInfo dibangPrintInfo = new DiBangPrintInfo();

                    dibangPrintInfo.PinMing = txtPinMing.Text.Trim();
                    dibangPrintInfo.CheHao = txtCheHao.Text.Trim();
                    dibangPrintInfo.ChengZhongDate = lblVDate.Text.Trim();
                    dibangPrintInfo.MaoZhong = txtMaoZhong.Text.Trim();
                    dibangPrintInfo.PiZhong = txtPiZhong.Text.Trim();
                    dibangPrintInfo.RongQiNum = txtRongQiNum.Text.Trim();
                    dibangPrintInfo.RongQiZhong = txtRongQiZhong.Text.Trim();
                    dibangPrintInfo.JingZhong = txtJingZhong.Text.Trim();

                    if (byteFirstPic != null)
                    {
                        dibangPrintInfo.FirstPic = Convert.ToBase64String(byteFirstPic);//报表图片显示
                    }

                    FrmDiBangPrint frmDiBangPrint = new FrmDiBangPrint();
                    frmDiBangPrint._DiBangPrintInfo = dibangPrintInfo;
                    frmDiBangPrint.ShowDialog();

                    this.Close();
                }
            }
            catch (Exception err)
            {
                MessageBoxEx.Show(err.Message, "Warming", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            //finally
            //{
            //    txtPwd.Clear();
            //    txtComment.Clear();

            //    txtPinMing.Clear();
            //    txtCheHao.Clear();
            //    txtOther.Clear();

            //    txtMaoZhong.Clear();
            //    txtPiZhong.Clear();
            //    txtRongQiNum.Clear();
            //    txtRongQiZhong.Clear();
            //    txtJingZhong.Clear();

            //    WeightMode = InputMode.None;
            //    //
            //    picFirst.Image = null;
            //    btnFirstPhoto.Text = "拍照";
            //}
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //lblVDate.Text = sqlExtend.GetSysTime();
            InfoSet();
        }

        private void InfoSet()
        {
            lblVDate.Text = sqlExtend.GetSysTime();

            //计算结果
            int iMaoZhong = 0;
            int iPiZhong = 0;
            int iRongQiZhong = 0;

            int.TryParse(txtMaoZhong.Text.Trim(), out iMaoZhong);
            int.TryParse(txtPiZhong.Text.Trim(), out iPiZhong);
            int.TryParse(txtRongQiZhong.Text.Trim(), out iRongQiZhong);

            int iJingZhong = iMaoZhong - iPiZhong - iRongQiZhong;

            txtJingZhong.Text = iJingZhong.ToString();
        }

        private bool DiBangCheck()
        {
            string strDiBangID = lblVDiBang_ID.Text;

            StringBuilder strb = new StringBuilder();
            strb.Append(@"SELECT CHENG_DATE,PIN_MING,CHE_HAO,WEIGHT,MaoZhong,PiZhong,RongQiNum,RongQiZhong,
JingZhong,OTHER,IMAGE_ID,CompleteFlag,CREATE_USER_ID,CREATE_TIME,LAST_EVENT_NAME,LAST_EVENT_USER_ID,
LAST_EVENT_TIMEKEY
FROM DB_DIBANG WHERE (COMPLETEFLAG!='Y' OR COMPLETEFLAG IS NULL) AND DIBANG_ID={0}DIBANG_ID");

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = string.Format(strb.ToString(), ConstParam.DbChar);
            cmd.Parameters.Add(new SqlParameter("DIBANG_ID", int.Parse(strDiBangID)));

            DataTable dt = sqlLib.GetDataSet(cmd).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                return true;
            }

            return false;
        }

        private void FrmDiBangSecInput_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.closeFlag = true;
            this._SerialPort.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(this.port_DataReceived);
            Thread.Sleep(200);

            //if (MessageBoxEx.Show("确定要退出吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            //{
            //    e.Cancel = false;
            //}
            //else
            //{
            //    e.Cancel = true;
            //}
        }

        private void txtRongQiNum_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(txtRongQiNum.Text.Trim()))
                {
                    int iRongQiNum = int.Parse(txtRongQiNum.Text.Trim());
                    int iAveRongQi = int.Parse(ConstParam.AveRongQi);
                    txtRongQiZhong.Text = (iRongQiNum * iAveRongQi).ToString();
                }
                else
                {
                    txtRongQiZhong.Clear();
                }
            }
            catch
            {
                MessageBoxEx.Show("输入的数字不正确!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtRongQiNum.Clear();
            }
        }
    }
}
